import { useState, useEffect } from 'react';
import { post, get } from '../services/api';
import { Form, Button, Space, Card, InputNumber, Select, message } from 'antd';

function GradeForm({ onClose, onSuccess }) {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [classes, setClasses] = useState([]);
  const [students, setStudents] = useState([]);
  const [selectedClass, setSelectedClass] = useState(null);

  useEffect(() => {
    fetchClasses();
  }, []);

  const fetchClasses = async () => {
    try {
      const response = await get('classes');
      setClasses(response.data || response);
    } catch (error) {
      console.error('获取班级列表失败:', error);
    }
  };

  const handleClassChange = (classId) => {
    const classInfo = classes.find(c => c.class_id === classId);
    setSelectedClass(classInfo);
    setStudents(classInfo?.students || []);
    form.setFieldsValue({ student_id: null }); // 清空学生选择
  };

  const handleSubmit = async (values) => {
    setLoading(true);
    try {
      await post('grades', values);
      message.success('成绩添加成功');
      form.resetFields();
      setSelectedClass(null);
      setStudents([]);
      onClose();
      if (onSuccess) onSuccess();
    } catch (error) {
      console.error('添加成绩失败:', error);
      message.error('添加失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Card
      style={{
        marginBottom: 24,
        boxShadow: '0 1px 2px rgba(0, 0, 0, 0.1)',
      }}
    >
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSubmit}
        initialValues={{
          student_id: null,
          class_id: null,
          grade: null,
        }}
      >
        <Form.Item
          name="class_id"
          label={<span style={{ fontSize: '16px' }}>班级</span>}
          rules={[{ required: true, message: '请选择班级！' }]}
        >
          <Select
            placeholder="请选择班级"
            style={{ fontSize: '16px' }}
            onChange={handleClassChange}
          >
            {classes.map(cls => (
              <Select.Option key={cls.class_id} value={cls.class_id}>
                {cls.class_name} - {cls.semester}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          name="student_id"
          label={<span style={{ fontSize: '16px' }}>学生</span>}
          rules={[{ required: true, message: '请选择学生！' }]}
        >
          <Select
            placeholder="请先选择班级"
            style={{ fontSize: '16px' }}
            disabled={!selectedClass}
          >
            {students.map(student => (
              <Select.Option key={student.student_id} value={student.student_id}>
                {student.student_name} ({student.student_id})
              </Select.Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          name="grade"
          label={<span style={{ fontSize: '16px' }}>成绩</span>}
          rules={[
            { required: true, message: '请输入成绩！' },
            { type: 'number', min: 0, max: 100, message: '成绩必须在0-100之间！' }
          ]}
        >
          <InputNumber
            style={{ width: '100%', fontSize: '16px' }}
            placeholder="请输入成绩（0-100）"
            min={0}
            max={100}
          />
        </Form.Item>

        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit" loading={loading} style={{ fontSize: '16px' }}>
              添加成绩
            </Button>
            <Button onClick={onClose} style={{ fontSize: '16px' }}>取消</Button>
          </Space>
        </Form.Item>
      </Form>
    </Card>
  );
}

export default GradeForm;